package com.mano233.server.controller;

import com.mano233.server.config.exception.PasswordEx;
import com.mano233.server.config.json.annotation.JsonCustomFilter;
import com.mano233.server.config.security.UserCustomDetailServiceImpl;
import com.mano233.server.config.security.UserCustomDetails;
import com.mano233.server.po.ResponseMessage;
import com.mano233.server.po.ResponseStatus;
import com.mano233.server.tool.JwtUtil;
import io.swagger.annotations.Api;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;


@RestController
@CrossOrigin(maxAge = 3600)
@Api("授权接口")
public class AuthorizeController {
    private final UserCustomDetailServiceImpl userCustomDetailService;

    public AuthorizeController(UserCustomDetailServiceImpl userCustomDetailService) {
        this.userCustomDetailService = userCustomDetailService;
    }

    @PostMapping("/login")
    @JsonCustomFilter(type = UserCustomDetails.class, filter = {"userPwd"})
    public ResponseMessage login(String userName, String pwd) {
        UserCustomDetails userDetails = userCustomDetailService.loadUserByUsername(userName);
        if (Objects.isNull(userDetails)) {
            throw new UsernameNotFoundException("找不到用户");
        }
        // todo 修改密码验证逻辑
        if (userDetails.getPassword().equals(pwd)) {
            userDetails.setToken(JwtUtil.signToken(userDetails.getUserId()));
            return new ResponseMessage(ResponseStatus.SUCCESS, userDetails);
        }
        throw new PasswordEx(userDetails.getUserName());
    }

    @GetMapping("/login")
    @JsonCustomFilter(type = UserCustomDetails.class, filter = {"userPwd"})
    public ResponseMessage login(Authentication authentication) {
        UserCustomDetails authDetails = (UserCustomDetails) authentication.getPrincipal();
        UserCustomDetails userDetails = userCustomDetailService.loadUserById(authDetails.getUserId());
        userDetails.setToken(authDetails.getToken());
        return new ResponseMessage(ResponseStatus.SUCCESS, userDetails);
    }
}
